﻿using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Lawn.AppServer
{
    public class DefaultMessageFactory:IMessageFactory
    {

        private IServiceProvider serviceProvider;

        private  OptionCommandType option;

        public DefaultMessageFactory(IServiceProvider _serviceProvider, IOptions<OptionCommandType> _option)
        {
            this.serviceProvider = _serviceProvider;
            this.option = _option.Value;
        }
        
        public IMessageHandler Creat(MessagePackageInfo packageInfo)
        {

            if (packageInfo == null)
            {
                return serviceProvider.GetRequiredService<NoSupportProtoMessageHandler>();
            }
            int key = packageInfo.Key;
            var type = option.Types.FirstOrDefault(x => x.Key == key).Value;
            if (type == null)
            {
                return serviceProvider.GetRequiredService<NoSupportProtoMessageHandler>();
            } 
            return serviceProvider.GetRequiredService(type) as IMessageHandler;


        }
    }
}